package com.keur.money.ui.user.act

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.viewpager.widget.ViewPager
import com.keur.money.R
import com.keur.money.base.utils.ImageUtil
import com.keur.money.base.utils.TitleBarUtil
import com.keur.money.databinding.ActMullaUserVipBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.MvpAct
import com.keur.money.ui.user.impl.KeurUserVipPresenterImpl
import com.keur.money.ui.user.view.IKeurUserVipView
import com.keur.money.utils.dialog.UserBirthdayBenefitsDialog
import com.keur.money.utils.dialog.UserGradeQADialog
import com.keur.money.utils.event.KeurEventData
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.KeurCustomDataHelper
import com.keur.money.weight.banner.XBannerUtils
import com.keur.money.weight.banner.entity.UserVipInfo
import com.keur.money.weight.banner.transformers.Transformer

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/14 19:40
 * @Annotation：用户VIP等级中心
 */
class KeurUserVipAct: MvpAct<IKeurUserVipView, KeurUserVipPresenterImpl>(),IKeurUserVipView {
    lateinit var binding: ActMullaUserVipBinding

    /**
     * 生日福利领取状态
     * -1: 未设置生日
     * 0 ：待领取
     * 1 ：已领取
     * 2 ：不可领取
     */
    private var birthdayBenefitsReceiveStatus = -1

    companion object {
        private const val INTENT_KEY_INDEX = "showIndex"
        fun start(context: Context, index: Int) {
            val intent = Intent(context, KeurUserVipAct::class.java)
            intent.putExtra(INTENT_KEY_INDEX, index)
            context.startActivity(intent)
        }
    }

    override fun createPresenter(): KeurUserVipPresenterImpl {
        return KeurUserVipPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaUserVipBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        binding.parentLayout.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)
        initMullaGradeBanner()
    }

    override fun initMullaListener() {
        //返回
        binding.imgBack.setOnClickListener {
            finish()
        }
        //客服
        binding.imgKefu.setOnClickListener {
            showMullaKefuDialog("Grade Center Page")
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER,"Grade Center Page")
        }

        //生日福利
        binding.birthdayLayout.setOnClickListener {
            when(birthdayBenefitsReceiveStatus){
                -1 -> {
                    //未设置生日 - 跳转到个人简介
                    onIntent(KeurUserProfileAct::class.java)
                }
                0 -> {
                    showMullaLoading(isTOuchOut = false, isCancel = true)
                    presenter.saveMullaUserBirthdayBenefitsReceiveTimeAction()
                }
            }
        }
    }

    override fun initMullaData() {
        presenter.loadMullaVipGradeListAction()
        presenter.loadMullaUserBirthdayBenefitsStatus()

        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.visibility = View.VISIBLE

            ImageUtil.instance?.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))
            binding.textLicenseDesc.text = licenseInfo.optString("desc")
            binding.textLicenseValue.text = licenseInfo.optString("companyName")
        }
    }

    /* 初始化banner */
    private fun initMullaGradeBanner() {
        // 设置XBanner的页面切换特效
        binding.xBanner.setPageTransformer(Transformer.Scale)
        // 设置XBanner页面切换的时间，即动画时长
        binding.xBanner.setPageChangeDuration(1000)
        binding.xBanner.setAutoPlayTime(3000)
        binding.xBanner.setSlideScrollMode(1)
        //设置是否允许用户手指滑动
        binding.xBanner.setAllowUserScrollable(true)
        //是否自动轮播
        binding.xBanner.setAutoPlayAble(false)
        //设置非自动轮播状态下是否可以循环切换
        binding.xBanner.setHandLoop(false)
        //显示指示器
        binding.xBanner.setPointsIsVisible(false)
        binding.xBanner.setShowIndicatorOnlyOne(false)
        //是否开启一屏多个模式
        binding.xBanner.setIsClipChildrenMode(true)
        //修改一屏多显模式左右间距
        binding.xBanner.setClipChildrenLeftRightMargin(XBannerUtils.dp2px(this, 20f), XBannerUtils.dp2px(this, 20f))

        //加载广告图片
        binding.xBanner.loadImage { banner, model, view, position ->
            //2、返回的图片路径为Object类型，你只需要强转成你传输的类型就行，切记不要胡乱强转！
            val item = model as UserVipInfo

            val itemLayout = view.findViewById<RelativeLayout>(R.id.itemLayout)
            itemLayout.setBackgroundResource(item.bannerResId)

            val imgMore = view.findViewById<ImageView>(R.id.imgMore)
            imgMore.setImageResource(item.moreIcon)

            val imgVipText = view.findViewById<ImageView>(R.id.imgVipText)
            imgVipText.setImageResource(item.vipText)

            val imgDoubt = view.findViewById<ImageView>(R.id.imgDoubt)
            imgDoubt.setImageResource(item.vipDoubt)

            val imgLable = view.findViewById<ImageView>(R.id.imgLable)
            imgLable.setImageResource(item.vipLable)

            val textNickName = view.findViewById<TextView>(R.id.textNickName)
            textNickName.setTextColor(item.colorId)
            textNickName.text = KeurCustomDataHelper.getMullaCustomUserName()

            val imgAvatar = view.findViewById<ImageView>(R.id.imgAvatar)
            imgAvatar.setImageResource(KeurCustomDataHelper.getMullaCustomUserAvatar())
        }
        binding.xBanner.setOnItemClickListener { banner, model, view, position ->
            val item = model as UserVipInfo
            //个人简介
            val profileLayout = view.findViewById<LinearLayout>(R.id.profileLayout)
            profileLayout.setOnClickListener {
                onIntent(KeurUserProfileAct::class.java)
            }
            //等级问答
            val qaLayout = view.findViewById<LinearLayout>(R.id.qaLayout)
            qaLayout.setOnClickListener {
                val qaDialog = UserGradeQADialog(this)
                qaDialog.show()
            }
        }
        binding.xBanner.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }
            override fun onPageSelected(position: Int) {
                showMullaGradeBackgroundResource(position)
            }
            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    /**
     * 获取查看的产品名称
     */
    private fun showDefaultIndex(): Int {
        var showIndex = getMullaUserVip() - 1
        intent.extras?.let {
            showIndex = it.getInt(INTENT_KEY_INDEX,0)
        }
        return showIndex
    }

    /**
     * 设置等级banner
     */
    override fun showMullaVipGradeList(gradeList: ArrayList<UserVipInfo>) {
        binding.xBanner.setBannerData(R.layout.item_mulla_vip_grade,gradeList)

        val curtIndex = showDefaultIndex()
        //当前VIP等级为1,不会触发onPageSelected 回调， 需要手动设置背景
        if (curtIndex == 0){
            showMullaGradeBackgroundResource(0)
        } else {
            binding.xBanner.bannerCurrentItem = curtIndex
        }
    }

    /**
     * 设置背景
     */
    private fun showMullaGradeBackgroundResource(position: Int){
        presenter.vipGradeList?.let {
            val item = it[position]
            binding.parentLayout.setBackgroundResource(item.backgroundResId)
            binding.textVipBenefits.text = String.format(getString(R.string.vip_benefits),item.vGrade)

            if (getMullaUserVip() < item.vip){//显示等级未达到
                binding.unableLayout.visibility = View.VISIBLE
            } else {
                binding.unableLayout.visibility = View.INVISIBLE
            }
            showMullaGradeBenefitsView(item)
        }
    }

    /**
     * 显示等级权益
     */
    private fun showMullaGradeBenefitsView(item: UserVipInfo){
        val benefitsObj = item.vipBenefits
        binding.imgDiscount.setImageResource(benefitsObj.optInt("discountIcon"))
        if (benefitsObj.optBoolean("discountUnlock")){
            binding.imgDiscountUnlock.visibility = View.VISIBLE
        } else {
            binding.imgDiscountUnlock.visibility = View.GONE
        }
        binding.textDiscountTitle.setTextColor(benefitsObj.optInt("titleColor"))
        when(item.vip){
            2 -> {
                //优惠券兑换折扣
                val customData = KeurCustomConfigsHelper.getMullaCustomData()
                val couponRateVip = customData?.optJSONArray("couponRateVip")
                couponRateVip?.let {
                    val couponRateVip2 = it.optDouble(1,1.0)
                    val showRate = (100 - (couponRateVip2 * 100)).toInt()
                    binding.textDiscountDesc.text = String.format(getString(benefitsObj.optInt("discountDes")),"$showRate%")
                }
                binding.textRepaymentDesc.text = String.format(getString(benefitsObj.optInt("repaymentDes")),"1.5")
                binding.textRepaymentDesc.setTextColor(Color.parseColor("#FFFF7121"))

            }
            3 -> {
                //优惠券兑换折扣
                val customData = KeurCustomConfigsHelper.getMullaCustomData()
                val couponRateVip = customData?.optJSONArray("couponRateVip")
                couponRateVip?.let {
                    val couponRateVip3 = it.optDouble(2,1.0)
                    val showRate = (100 - (couponRateVip3 * 100)).toInt()
                    binding.textDiscountDesc.text = String.format(getString(benefitsObj.optInt("discountDes")),"$showRate%")
                }
                binding.textRepaymentDesc.text = String.format(getString(benefitsObj.optInt("repaymentDes")),"2")
                binding.textRepaymentDesc.setTextColor(Color.parseColor("#FFFF7121"))
            }
            else -> {
                binding.textDiscountDesc.text = getString(benefitsObj.optInt("discountDes"))
                binding.textRepaymentDesc.text = getString(benefitsObj.optInt("repaymentDes"))
                binding.textRepaymentDesc.setTextColor(benefitsObj.optInt("desColor"))
            }
        }
        binding.textDiscountDesc.setTextColor(benefitsObj.optInt("desColor"))

        binding.imgRepayment.setImageResource(benefitsObj.optInt("repaymentIcon"))
        if (benefitsObj.optBoolean("repaymentUnlock")){
            binding.imgRepaymentUnlock.visibility = View.VISIBLE
        } else {
            binding.imgRepaymentUnlock.visibility = View.GONE
        }
        binding.textRepaymentTitle.setTextColor(benefitsObj.optInt("titleColor"))

        binding.imgBirthday.setImageResource(benefitsObj.optInt("birthdayIcon"))
        binding.textBirthdayTitle.setTextColor(benefitsObj.optInt("titleColor"))

        binding.imgOther.setImageResource(benefitsObj.optInt("otherIcon"))
        binding.textOtherTitle.setTextColor(benefitsObj.optInt("titleColor"))
        binding.textOtherDesc.text = getString(benefitsObj.optInt("otherDes"))
        binding.textOtherDesc.setTextColor(benefitsObj.optInt("desColor"))
    }

    /**
     * 设置生日福利状态 status
     * -1: 未设置生日
     * 0 ：待领取
     * 1 ：已领取
     * 2 ：不可领取
     */
    override fun showMullaUserBirthdayBenefitsView(status: Int){
        birthdayBenefitsReceiveStatus = status
        when(status){
            -1 -> {
                //未设置生日 - 点击跳转到 “个人简介” 页面
                binding.textBirthdayDesc.text = getString(R.string.vip_birthday_not_set)
                binding.textBirthdayDesc.setTextColor(Color.parseColor("#FF9599BA"))
                binding.birthdayLayout.isEnabled = true
            }
            0 -> {
                //待领取 - 点击领取
                binding.textBirthdayDesc.text = getString(R.string.vip_birthday_receive_wait)
                binding.textBirthdayDesc.setTextColor(Color.parseColor("#FFFFC971"))
                binding.birthdayLayout.isEnabled = true
            }
            1 -> {
                //已领取 - 不可点击
                binding.textBirthdayDesc.text = getString(R.string.vip_birthday_received)
                binding.textBirthdayDesc.setTextColor(Color.parseColor("#FF8CFF98"))
                binding.birthdayLayout.isEnabled = false
            }
            else -> {
                //不可领取- 不可点击
                binding.textBirthdayDesc.text = getString(R.string.vip_birthday_tips)
                binding.textBirthdayDesc.setTextColor(Color.parseColor("#FF9599BA"))
                binding.birthdayLayout.isEnabled = false
            }
        }
    }

    /**
     * 生日福利领取成功
     */
    override fun showMullaUserBirthdayBenefitsReceiveSuccess(points: String) {
        val birthdayDialog = UserBirthdayBenefitsDialog(this)
        birthdayDialog.setCancelable(true)
        birthdayDialog.setCanceledOnTouchOutside(false)
        birthdayDialog.show()
        birthdayDialog.showMullaUserBirthdayPoints(points)
    }

    override fun onKeurEvent(event: KeurEventData) {
        //刷新自定义数据成功
        if (event.eventType == KeurEventData.TYPE.KEUR_CUSTOM_DATA_REFRESHED){
            presenter.loadMullaVipGradeListAction()
            presenter.loadMullaUserBirthdayBenefitsStatus()
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_GRADE_CENTER_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_GRADE_CENTER_END)
    }
}